package com.ruoyi.SuveryInterface.DegreesSuvery;

import com.alibaba.fastjson.JSON;
import com.ruoyi.SuveryInterface.Imp.domain.SysCredit;
import com.ruoyi.SuveryInterface.Imp.domain.SysDegrees;
import com.ruoyi.SuveryInterface.Imp.domain.SysMessage;
import com.ruoyi.SuveryInterface.Imp.mapper.SysDegreeDetailsMapper;
import com.ruoyi.SuveryInterface.Imp.mapper.SysDegreesMapper;
import com.ruoyi.SuveryInterface.SuveryUtils.ClientRequest;
import com.ruoyi.SuveryInterface.SuveryUtils.Constants;
import com.ruoyi.SuveryInterface.SuveryUtils.CustomerKeys;
import com.ruoyi.SuveryInterface.SuveryUtils.util.HttpClientUtils;
import com.ruoyi.SuveryInterface.SuveryUtils.util.RsaSignature;
import com.ruoyi.SuveryInterface.SuveryUtils.util.SerialNumberUtil;
import com.ruoyi.SuveryInterface.SuveryUtils.util.ThreeDesUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

// 银行卡二要素 卡号 手机号
public class DegreesSuveryThree {

	private SysDegreesMapper degreesMapper;

	private SysDegreeDetailsMapper degreeDetailsMapper;

	public SysDegreesMapper getDegreesMapper() {
		return degreesMapper;
	}

	public DegreesSuveryThree(SysDegreesMapper degreesMapper, SysDegreeDetailsMapper degreeDetailsMapper) {
		this.degreesMapper = degreesMapper;
		this.degreeDetailsMapper = degreeDetailsMapper;
	}

	public void setDegreesMapper(SysDegreesMapper degreesMapper) {
		this.degreesMapper = degreesMapper;
	}

	public SysDegreeDetailsMapper getDegreeDetailsMapper() {
		return degreeDetailsMapper;
	}

	public void setDegreeDetailsMapper(SysDegreeDetailsMapper degreeDetailsMapper) {
		this.degreeDetailsMapper = degreeDetailsMapper;
	}

	private static String baseUrl ="https://api.jizhengyun.com/v1.0/realname/";

	public SysDegrees QueryDegrees(String name,String certificate_num,String id_card,Long orderId) throws Exception {

//		String acct_no = "6222030502005030526";
//		String phone = "13643669790";
//		String name = "吕宇宏";
//		String certificate_num = "141124200308110076";
//
//		String id_card = "141124200308110076";
		if (true) {
			throw new Exception();
		}


		String cert_type = "";
		// 订单号
		String out_trade_no = SerialNumberUtil.createBillNo();
		String tran_time = "2024-07-01 12:01:30";
		String verify_type = "04259";
		//测试商户号
		String cutomer_code = CustomerKeys.customer_code;
		String url = baseUrl + cutomer_code;
		// 3des密钥
		String des_key = CustomerKeys.des_key;
		//RSA私钥
		String rsa_key = CustomerKeys.rsa_key;
		ClientRequest molinkRequest = new ClientRequest();
		molinkRequest.setOut_trade_no(out_trade_no);
		molinkRequest.setTran_time(tran_time);
		molinkRequest.setVerify_type(verify_type);
		molinkRequest.setCustomer_code(cutomer_code);
//		molinkRequest.setAcct_no(acct_no);
//		molinkRequest.setPhone(phone);
		molinkRequest.setName(name);
		molinkRequest.setCertificate_num(certificate_num);
		molinkRequest.setId_card(id_card);





		StringBuilder builder = new StringBuilder();
		builder.append(Constants.out_trade_no.toUpperCase() + "=" + out_trade_no);
		builder.append("&" + Constants.tran_time.toUpperCase() + "=" + tran_time);
		builder.append("&" + Constants.verify_type.toUpperCase() + "=" + verify_type);
//		builder.append("&" + Constants.acct_no.toUpperCase() + "=" + acct_no);
//		builder.append("&" + Constants.phone.toUpperCase() + "=" + phone);
		builder.append("&" + Constants.name.toUpperCase() + "=" + name);
		builder.append("&" + "certificate_num".toUpperCase() + "=" + certificate_num);
		builder.append("&" + "id_card".toUpperCase() + "=" + id_card);



		System.out.println("加签信息:"+builder.toString());
		String sign = RsaSignature.rsaSign(builder.toString(), rsa_key, Constants.CHARSET_UTF8);
		molinkRequest.setSign(sign);

		String json = JSON.toJSONString(molinkRequest);
		System.out.println("发送报文信息:"+json.toString());
		byte[] keybyte = des_key.getBytes();
		byte[] requsest = ThreeDesUtil.encryptMode(keybyte, json.getBytes());
		String code = HttpClientUtils.ysPost(url, ThreeDesUtil.byte2Hex(requsest));
		System.out.println(code);
		SysDegrees degreesEntity = getDegreesEntity(code);

		degreesEntity.setOrderId(orderId);

		degreesMapper.insertSysDegrees(degreesEntity);


		if (degreesEntity.getCode().equals("1009")) {
			throw new ServiceException("参数类型错误");
		}
		else if (!degreesEntity.getCode().equals("0000")) {
			throw new RuntimeException();
		}
		List<com.alibaba.fastjson.JSONObject> degreeDetails = degreesEntity.getJsonObjects();
//        degreeDetailsService.saveBatch(degreeDetails);
		if (!CollectionUtils.isEmpty(degreeDetails)) {
			for (com.alibaba.fastjson.JSONObject degreeDetail : degreeDetails) {
				degreeDetail.put("sysDegreesId",degreesEntity.getId());
			}
			degreeDetailsMapper.insertBatch(degreeDetails);
		}











		// 验签流程：
		// 1、获取验签参数
		// 2、拼接验签字符串
		// 3、使用验签方法进行验签

		try {
			JSONObject jsonObject = JSONObject.fromObject(code);
			String signContent = jsonObject.getString("sign");
			String CODE = jsonObject.getString("code");
			String MESSAGE = jsonObject.getString("message");
			String OUT_TRADE_NO = jsonObject.getString("out_trade_no");
			String TRAN_AMT = jsonObject.getString("tran_amt");
			String TRAN_TIME = jsonObject.getString("tran_time");

			StringBuilder signbuilder = new StringBuilder();
			signbuilder.append(Constants.code.toUpperCase() + "=" + CODE);
			signbuilder.append("&" + Constants.message.toUpperCase() + "=" + MESSAGE);
			signbuilder.append("&" + Constants.out_trade_no.toUpperCase() + "=" + OUT_TRADE_NO);
			signbuilder.append("&" + Constants.tran_amt.toUpperCase() + "=" + TRAN_AMT);
			signbuilder.append("&" + Constants.tran_time.toUpperCase() + "=" + TRAN_TIME);

			// 系统公钥
			String key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9TbGYWcBGAWmB2f6uzuZQeZ8algiHz63OXlumUAX0Dlyh+15RQ3VKs//bsgx9RUaSzyae1vmXtKGlYzy/jk8dqljTPolyJZ6rrpJ9F/kzZpHHYYmLAQX+LVGSNYoxormAvpTg2sce/pJWyr6fiHvNyM8YXQnxQwDkO4Ert3sELQIDAQAB";
			boolean signResult = RsaSignature.rsaCheckContent(signbuilder.toString(), signContent, key,
					Constants.CHARSET_UTF8);
			if (signResult) {
				System.out.println("验签成功");
			} else {
				System.out.println("验签失败");
				throw new ServiceException("验签失败");
			}
		} catch (Exception e) {
			throw new ServiceException("验签出现异常");
		}
		return degreesEntity;
	}

	private static String changeCharSet(String str, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			// 用默认字符编码解码字符串。
			byte[] bs = str.getBytes();
			// 用新的字符编码生成字符串
			return new String(bs, newCharset);
		}
		return str;
	}

	private SysDegrees getDegreesEntity(String code) {
		SysCredit sysCredit = com.alibaba.fastjson.JSONObject.parseObject(code, SysCredit.class);
		SysDegrees sysDegrees = new SysDegrees();

		if (sysCredit.getCode().equals("0000")) {
			SysMessage sysMessage = com.alibaba.fastjson.JSONObject.parseObject(sysCredit.getMessage(), SysMessage.class);

			String data = sysMessage.getData();
			if (!StringUtils.isEmpty(data)){
				List<com.alibaba.fastjson.JSONObject> jsonObjects =new ArrayList<>();
				if (data.charAt(0)=='{') {
					//说明只有一个数据
					com.alibaba.fastjson.JSONObject sysDegreeDetails = com.alibaba.fastjson.JSONObject.parseObject(sysMessage.getData());
					jsonObjects.add(sysDegreeDetails);
				}
				else {
					//有多个数据
					List<com.alibaba.fastjson.JSONObject> sysDegreeDetails = com.alibaba.fastjson.JSONObject.parseObject(sysMessage.getData(), List.class);

					jsonObjects=sysDegreeDetails;
				}



				sysDegrees.setJsonObjects(jsonObjects);
			}
			BeanUtils.copyProperties(sysMessage,sysDegrees);

		}
		else {
			sysDegrees.setResultMsg(sysCredit.getMessage());
			sysDegrees.setResult("0");
		}






		sysDegrees.setCode(sysCredit.getCode());
		sysDegrees.setSign(sysCredit.getSign());
		sysDegrees.setOutTradeNo(sysCredit.getOut_trade_no());
		sysDegrees.setTranAmt(sysCredit.getTran_amt());
		sysDegrees.setTranTime(sysCredit.getTran_time());


		sysDegrees.setCreateTime(new Date());

		return sysDegrees;
	}



}
